﻿namespace Bizspoke.BizTalk.Brma
{
    using Microsoft.BizTalk.Tracing;
    using Microsoft.BizTalk.Tracking;
    using System;
    using System.Collections;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.Drawing;
    using System.Globalization;
    using System.Management;
    using System.Runtime.InteropServices;
    using System.Web;
    using System.Windows.Forms;
    using Bizspoke.BizTalk.Tracking;
    using System.Collections.Generic;

    [Guid("77F5A29A-2B19-40CC-9E95-3638763DE040"), ComVisible(true)]
    public class SvcInstList
    {
        internal const string ActiveXGuid = "77F5A29A-2B19-40CC-9E95-3638763DE040";
        private const string DB_CONN_STR = "server='{0}';database='{1}';Trusted_Connection=yes;Pooling=false;Connect Timeout={2};";
        private const uint E_FAIL = 0x80004005;
        private Hashtable m_htblQueues = new Hashtable();
        private string m_sDtaDB;
        private string m_sDtaServer;
        private ArrayList m_siSvcInstList;
        private string m_sWmiServer;
        private const int MAX_SP_PARAM_LEN = 0xbb8;
        private const string SUSPQ_Path = "MSBTS_HostQueue.";
        private const string SUSPQ_Scope = @"\ROOT\MicrosoftBizTalkServer";
        private const string WORKQ_Path = "MSBTS_HostQueue.";
        private const string WORKQ_Scope = @"\ROOT\MicrosoftBizTalkServer";

        public SvcInstList(string sDtaServer, string sDtaDB, string sWmiServer)
        {
            new LockDownUnsafeTypes();
            string str = this.DecodeFromUrl(sDtaServer);
            string str2 = this.DecodeFromUrl(sDtaDB);
            string str3 = this.DecodeFromUrl(sWmiServer);
            this.m_sWmiServer = str3;
            this.m_sDtaServer = str;
            this.m_sDtaDB = str2;
            this.m_siSvcInstList = new ArrayList();
            ConfigurationManager.GetSection("system.diagnostics");
        }

        public int Add(string sGroupName, string sAppTypeName, string sInstID)
        {
            string str = this.DecodeFromUrl(sGroupName);
            string str2 = this.DecodeFromUrl(sAppTypeName);
            string str3 = this.DecodeFromUrl(sInstID);
            SvcInstInfo info = new SvcInstInfo(str, str2, str3);
            Hashtable queueInstList = this.GetQueueInstList(info.GroupBy);
            int num = -1;
            string key = info.InstID.ToUpper(CultureInfo.InvariantCulture).Trim(new char[] { '{', '}' });
            if (!queueInstList.Contains(key))
            {
                queueInstList.Add(key, info);
                num = this.m_siSvcInstList.Add(info);
            }
            return num;
        }

        public int AddWQ(string sGroupName, string sAppTypeName, string sInstID, string sServiceID, string sServiceClassID, string sMsgID, string sMsgBoxSrv, string sMsgBoxDbName)
        {
            string str = this.DecodeFromUrl(sGroupName);
            string str2 = this.DecodeFromUrl(sAppTypeName);
            string str3 = this.DecodeFromUrl(sInstID);
            string str4 = this.DecodeFromUrl(sServiceID);
            string str5 = this.DecodeFromUrl(sServiceClassID);
            string str6 = this.DecodeFromUrl(sMsgID);
            string str7 = this.DecodeFromUrl(sMsgBoxSrv);
            string str8 = this.DecodeFromUrl(sMsgBoxDbName);
            SvcInstInfo info = new SvcInstInfo(str, str2, str3, str4, str5, str6, str8, str7);
            Hashtable queueInstList = this.GetQueueInstList(info.GroupBy);
            int num = -1;
            string key = info.InstID.ToUpper(CultureInfo.InvariantCulture).Trim(new char[] { '{', '}' });
            if (!queueInstList.Contains(key))
            {
                queueInstList.Add(key, info);
                num = this.m_siSvcInstList.Add(info);
            }
            return num;
        }

        private void callWmiWqSp(string Scope, string Path, string Method, string[] InstIdList, string[] ClassIdList, string[] TypeIdList, bool bResume, bool bDebug)
        {
            ManagementScope scope = new ManagementScope(Scope);
            scope.Connect();
            ManagementPath path = new ManagementPath(Admin.FixWMIPath(Path));
            ManagementObject obj2 = new ManagementObject(scope, path, null);
            ManagementBaseObject methodParameters = obj2.GetMethodParameters(Method);
            methodParameters["ServiceClassID"] = ClassIdList;
            methodParameters["ServiceTypeID"] = TypeIdList;
            methodParameters["ServiceInstanceID"] = InstIdList;
            if (bResume)
            {
                int num;
                if (bDebug)
                {
                    num = 2;
                }
                else
                {
                    num = 1;
                }
                methodParameters["ResumeMode"] = num;
            }
            obj2.InvokeMethod(Method, methodParameters, null);
        }

        public void Clear()
        {
            this.m_siSvcInstList.Clear();
            this.m_htblQueues.Clear();
        }

        private string DecodeFromUrl(string val)
        {
            return HttpUtility.UrlDecode(val);
        }

        private string EncodeForUrl(string val)
        {
            return HttpUtility.UrlEncodeUnicode(val);
        }

        private bool ExecQueueMethod(string sScope, string sPathPrefix, string sMethod, bool bResume, bool bDebug)
        {
            bool flag2;
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                bool flag = true;
                this.ResolveUnknownQueuePaths();
                foreach (string str in this.m_htblQueues.Keys)
                {
                    uint errorCode = 0;
                    string errorMesg = "";
                    Hashtable hashtable = (Hashtable) this.m_htblQueues[str];
                    if (str.Length == 0)
                    {
                        errorCode = 0x80004005;
                        errorMesg = "Queue not found.";
                    }
                    else
                    {
                        try
                        {
                            string format = "{0},MgmtDbNameOverride=\"{1}\",MgmtDbServerOverride=\"{2}\"";
                            string path = string.Format(CultureInfo.InvariantCulture, format, new object[] { sPathPrefix + str, Preferences.MgmtDBName, Preferences.MgmtDBServer });
                            string[] instIdList = new string[hashtable.Count];
                            string[] classIdList = new string[hashtable.Count];
                            string[] typeIdList = new string[hashtable.Count];
                            int index = 0;
                            foreach (SvcInstInfo info in hashtable.Values)
                            {
                                instIdList[index] = this.VerifyGuidAndConvertToString(info.InstID);
                                classIdList[index] = this.VerifyGuidAndConvertToString(info.ServiceClassID);
                                typeIdList[index] = this.VerifyGuidAndConvertToString(info.AgentSrvID);
                                index++;
                            }
                            this.callWmiWqSp(sScope, path, sMethod, instIdList, classIdList, typeIdList, bResume, bDebug);
                        }
                        catch (ManagementException exception)
                        {
                            Trace.Tracer.TraceMessage(4, "BTSHATAPP: Exception {0} at {1}", new object[] { exception.Message, exception.StackTrace });
                            errorCode = (uint) exception.ErrorCode;
                            errorMesg = ExceptionMessageProvider.GetExceptionErrorMessage(exception);
                        }
                        catch (COMException exception2)
                        {
                            Trace.Tracer.TraceMessage(4, "BTSHATAPP: Exception {0} at {1}", new object[] { exception2.Message, exception2.StackTrace });
                            errorCode = (uint) exception2.ErrorCode;
                            errorMesg = ExceptionMessageProvider.GetExceptionErrorMessage(exception2);
                        }
                        catch (Exception exception3)
                        {
                            Trace.Tracer.TraceMessage(4, "BTSHATAPP: Exception {0} at {1}", new object[] { exception3.Message, exception3.StackTrace });
                            errorCode = 0x80004005;
                            errorMesg = ExceptionMessageProvider.GetExceptionErrorMessage(exception3);
                        }
                    }
                    if (errorCode != 0)
                    {
                        flag = false;
                        foreach (SvcInstInfo info2 in hashtable.Values)
                        {
                            info2.SetError(errorCode, errorMesg);
                        }
                    }
                }
                flag2 = flag;
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
            return flag2;
        }

        public object GetItem(int index)
        {
            if ((index < 0) || (index >= this.m_siSvcInstList.Count))
            {
                throw new IndexOutOfRangeException();
            }
            return this.m_siSvcInstList[index];
        }

        internal Hashtable GetQueueInstList(string sQueuePath)
        {
            Hashtable hashtable = (Hashtable) this.m_htblQueues[sQueuePath];
            if (hashtable == null)
            {
                hashtable = new Hashtable();
                this.m_htblQueues.Add(sQueuePath, hashtable);
            }
            return hashtable;
        }

        [ComRegisterFunction]
        private static void RegisterServer(System.Type t)
        {
            ComCategoryHelper.RegisterImplementedCategory("77F5A29A-2B19-40CC-9E95-3638763DE040", ComCategoryHelper.CatId_SafeForScripting);
        }

        private void ResolveUnknownQueuePaths()
        {
            Hashtable hashtable = new Hashtable();
            string selectConnectionString = string.Format(CultureInfo.InvariantCulture, "server='{0}';database='{1}';Trusted_Connection=yes;Pooling=false;Connect Timeout={2};", new object[] { this.m_sDtaServer, this.m_sDtaDB, Preferences.ConnectionTimeout });
            SqlDataAdapter adapter = new SqlDataAdapter("", selectConnectionString);
            foreach (string str2 in this.m_htblQueues.Keys)
            {
                Hashtable hashtable2 = (Hashtable) this.m_htblQueues[str2];
                string str3 = "";
                DataTable dataTable = new DataTable();
                dataTable.Locale = CultureInfo.InvariantCulture;
                int count = 0;
                foreach (SvcInstInfo info in hashtable2.Values)
                {
                    count++;
                    if (info.FullyQualifiedInstance)
                    {
                        Hashtable hashtable3 = (Hashtable) hashtable[info.GroupBy];
                        if (hashtable3 == null)
                        {
                            hashtable3 = new Hashtable();
                            hashtable.Add(info.GroupBy, hashtable3);
                        }
                        string key = info.InstID.ToUpper(CultureInfo.InvariantCulture);
                        if (!hashtable3.Contains(key))
                        {
                            hashtable3.Add(key, info);
                        }
                        continue;
                    }
                    str3 = str3 + "''" + info.InstID + "'',";
                    if ((str3.Length > 0xbb8) || (count == hashtable2.Count))
                    {
                        str3 = str3.Remove(str3.Length - 1, 1);
                        adapter.SelectCommand.CommandText = string.Format(CultureInfo.InvariantCulture, "exec dtasp_GetSvcInstMsgBoxInfo N'{0}'", new object[] { str3 });
                        adapter.Fill(dataTable);
                        int num1 = dataTable.Rows.Count;
                        str3 = "";
                    }
                }
                count = hashtable2.Count;
                foreach (DataRow row in dataTable.Rows)
                {
                    Guid guid = new Guid(row["uidServiceInstanceId"].ToString());
                    string str5 = guid.ToString("B").ToUpper(CultureInfo.InvariantCulture).Trim(new char[] { '{', '}' });
                    SvcInstInfo info2 = (SvcInstInfo) hashtable2[str5];
                    if (info2 != null)
                    {
                        info2.GroupName = row["strGroupName"].ToString();
                        info2.AgentSrvID = row["uidAgentSrvID"].ToString();
                        if (!info2.AgentSrvID.StartsWith("{", StringComparison.Ordinal))
                        {
                            info2.AgentSrvID = "{" + info2.AgentSrvID + "}";
                        }
                        info2.ServiceClassID = row["uidServiceClassID"].ToString();
                        if (!info2.ServiceClassID.StartsWith("{", StringComparison.Ordinal))
                        {
                            info2.ServiceClassID = "{" + info2.ServiceClassID + "}";
                        }
                        info2.AppTypeName = row["strHostName"].ToString();
                        Hashtable hashtable4 = (Hashtable) hashtable[info2.GroupBy];
                        if (hashtable4 == null)
                        {
                            hashtable4 = new Hashtable();
                            hashtable.Add(info2.GroupBy, hashtable4);
                        }
                        string str6 = info2.InstID.ToUpper(CultureInfo.InvariantCulture).Trim(new char[] { '{', '}' });
                        if (!hashtable4.Contains(str6))
                        {
                            hashtable4.Add(str6, info2);
                        }
                    }
                }
            }
            this.m_htblQueues = hashtable;
        }

        public bool ResumeDebugInstances()
        {
            bool flag = true;
            if (this.m_htblQueues.Count > 0)
            {
                string sScope = string.Format(CultureInfo.InvariantCulture, @"\ROOT\MicrosoftBizTalkServer", new object[0]);
                string sPathPrefix = "MSBTS_HostQueue.";
                string exceptionErrorMessage = string.Empty;
                try
                {
                    flag = this.ExecQueueMethod(sScope, sPathPrefix, "ResumeServiceInstancesByID", true, true);
                }
                catch (Exception exception)
                {
                    Trace.Tracer.TraceMessage(4, "BTSHATAPP: Exception {0} at {1}", new object[] { exception.Message, exception.StackTrace });
                    flag = false;
                    exceptionErrorMessage = ExceptionMessageProvider.GetExceptionErrorMessage(exception);
                }
                if (flag)
                {
                    ErrorDlg.ShowWarning(SharedRes.NavCtrl.GetString("STR_RESUMEBP_SUCCESS"));
                    return flag;
                }
                string sError = SharedRes.NavCtrl.GetString("STR_RESUMEBP_FAILURE");
                foreach (string str5 in this.m_htblQueues.Keys)
                {
                    Hashtable hashtable = (Hashtable) this.m_htblQueues[str5];
                    if (hashtable != null)
                    {
                        foreach (SvcInstInfo info in hashtable.Values)
                        {
                            if (!string.IsNullOrEmpty(info.ErrorMesg))
                            {
                                sError = sError + "\n";
                                sError = sError + info.ErrorMesg;
                            }
                        }
                    }
                }
                if (0 < exceptionErrorMessage.Length)
                {
                    sError = sError + "\n" + exceptionErrorMessage;
                }
                ErrorDlg.ShowError(sError);
            }
            return flag;
        }

        public bool ResumeInstances()
        {
            bool flag = true;
            if (this.m_htblQueues.Count > 0)
            {
                string sScope = string.Format(CultureInfo.InvariantCulture, @"\ROOT\MicrosoftBizTalkServer", new object[0]);
                string sPathPrefix = "MSBTS_HostQueue.";
                string exceptionErrorMessage = string.Empty;
                try
                {
                    flag = this.ExecQueueMethod(sScope, sPathPrefix, "ResumeServiceInstancesByID", true, false);
                }
                catch (Exception exception)
                {
                    Trace.Tracer.TraceMessage(4, "BTSHATAPP: Exception {0} at {1}", new object[] { exception.Message, exception.StackTrace });
                    flag = false;
                    exceptionErrorMessage = ExceptionMessageProvider.GetExceptionErrorMessage(exception);
                }
                if (flag)
                {
                    ErrorDlg.ShowWarning(SharedRes.NavCtrl.GetString("STR_RESUME_SUCCESS"));
                    return flag;
                }
                string sError = SharedRes.NavCtrl.GetString("STR_RESUME_FAILURE");
                if (0 < exceptionErrorMessage.Length)
                {
                    sError = sError + "\n" + exceptionErrorMessage;
                }
                ErrorDlg.ShowError(sError);
            }
            return flag;
        }

        public List<TrackedMessage> SaveMessagesToFile(string sWmiServer, string sMgmtDBSrv, string sMgmtDB)
        {
            List<TrackedMessage> statuses = new List<TrackedMessage>();
            string str5;
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                string wmiSrv = this.DecodeFromUrl(sWmiServer);
                string mgmtDBSrv = this.DecodeFromUrl(sMgmtDBSrv);
                string mgmtDB = this.DecodeFromUrl(sMgmtDB);
                TrackedMessageInfo[] msgList = new TrackedMessageInfo[this.m_siSvcInstList.Count];
                if (msgList.Length == 0)
                {
                    ErrorDlg.ShowWarning(SharedRes.NavCtrl.GetString("wrn_CouldNotFindAnyMessageFlowRecordsWhenSavingAllMsgBodies"));
                    return statuses;
                }
                for (int i = 0; i < this.m_siSvcInstList.Count; i++)
                {
                    SvcInstInfo info = (SvcInstInfo) this.m_siSvcInstList[i];
                    if (info != null)
                    {
                        msgList[i].MessageBoxName = info.MsgBoxDbName;
                        msgList[i].MessageBoxSrv = info.MsgBoxSrv;
                        msgList[i].GroupName = info.GroupName;
                        msgList[i].Host = info.AppTypeName;
                        msgList[i].SvcGUID = info.InstID;
                        msgList[i].MessageGUID = info.MsgID;
                    }
                }
                statuses = Admin.SaveMessageArrayToFile(msgList, wmiSrv, mgmtDBSrv, mgmtDB, null, null, true);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
            return statuses;
        }

        private void SetError(int index, uint nErrorCode, string sErrorMesg)
        {
            if ((index < 0) || (index >= this.m_siSvcInstList.Count))
            {
                throw new IndexOutOfRangeException();
            }
            ((SvcInstInfo) this.m_siSvcInstList[index]).SetError(nErrorCode, sErrorMesg);
        }

        public bool SuspendInstances()
        {
            bool flag = true;
            if (this.m_htblQueues.Count > 0)
            {
                string sScope = string.Format(CultureInfo.InvariantCulture, @"\ROOT\MicrosoftBizTalkServer", new object[0]);
                string sPathPrefix = "MSBTS_HostQueue.";
                string exceptionErrorMessage = string.Empty;
                try
                {
                    flag = this.ExecQueueMethod(sScope, sPathPrefix, "SuspendServiceInstancesByID", false, false);
                }
                catch (Exception exception)
                {
                    Trace.Tracer.TraceMessage(4, "BTSHATAPP: Exception {0} at {1}", new object[] { exception.Message, exception.StackTrace });
                    flag = false;
                    exceptionErrorMessage = ExceptionMessageProvider.GetExceptionErrorMessage(exception);
                }
                if (flag)
                {
                    ErrorDlg.ShowWarning(SharedRes.NavCtrl.GetString("STR_SUSPEND_SUCCESS"));
                    return flag;
                }
                string sError = SharedRes.NavCtrl.GetString("STR_SUSPEND_FAILURE");
                if (0 < exceptionErrorMessage.Length)
                {
                    sError = sError + "\n" + exceptionErrorMessage;
                }
                ErrorDlg.ShowError(sError);
            }
            return flag;
        }

        public bool TerminateInstances()
        {
            bool flag = true;
            if (this.m_htblQueues.Count > 0)
            {
                ResourcesNav nav = new ResourcesNav();
                string msg = nav.GetString("confirm_TerminateInstances");
                string caption = nav.GetString("confirm_Terminate_Caption");
                DialogResult result = new ErrorDlg(msg, caption, "ConfirmTerminateInstances", SystemIcons.Warning, MessageBoxButtons.YesNo, MessageBoxDefaultButton.Button2).ShowDialog();
                if (DialogResult.Yes != result)
                {
                    return false;
                }
                string sScope = string.Format(CultureInfo.InvariantCulture, @"\ROOT\MicrosoftBizTalkServer", new object[0]);
                string sPathPrefix = "MSBTS_HostQueue.";
                string exceptionErrorMessage = string.Empty;
                try
                {
                    flag = this.ExecQueueMethod(sScope, sPathPrefix, "TerminateServiceInstancesByID", false, false);
                }
                catch (Exception exception)
                {
                    Trace.Tracer.TraceMessage(4, "BTSHATAPP: Exception {0} at {1}", new object[] { exception.Message, exception.StackTrace });
                    flag = false;
                    exceptionErrorMessage = ExceptionMessageProvider.GetExceptionErrorMessage(exception);
                }
                if (flag)
                {
                    ErrorDlg.ShowWarning(SharedRes.NavCtrl.GetString("STR_TERMINATE_SUCCESS"));
                    return flag;
                }
                string sError = SharedRes.NavCtrl.GetString("STR_TERMINATE_FAILURE");
                if (0 < exceptionErrorMessage.Length)
                {
                    sError = sError + "\n" + exceptionErrorMessage;
                }
                ErrorDlg.ShowError(sError);
            }
            return flag;
        }

        [ComUnregisterFunction]
        private static void UnregisterServer(System.Type t)
        {
            ComCategoryHelper.UnregisterImplementedCategory("77F5A29A-2B19-40CC-9E95-3638763DE040", ComCategoryHelper.CatId_SafeForScripting);
        }

        private string VerifyGuidAndConvertToString(string sGuid)
        {
            string str = new Guid(sGuid).ToString();
            if (!str.StartsWith("{", StringComparison.Ordinal))
            {
                str = "{" + str + "}";
            }
            return str;
        }

        public int Count
        {
            get
            {
                return this.m_siSvcInstList.Count;
            }
        }
    }
}

